<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" @close="handleClose">
    <el-form ref="contactForm" :model="form" :rules="rules" label-width="80px">
      <!-- 日期 -->
      <el-form-item label="日期" prop="date">
        <el-date-picker
            v-model="form.date"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
        ></el-date-picker>
      </el-form-item>

      <!-- 姓名 -->
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>

      <!-- 省份 -->
      <el-form-item label="省份" prop="province">
        <el-select v-model="form.province" placeholder="请选择省份" @change="handleProvinceChange" >
          <el-option
              v-for="province in provinces"
              :key="province.value"
              :label="province.label"
              :value="province.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 城市 -->
      <el-form-item label="城市" prop="city">
        <el-select v-model="form.city" placeholder="请选择城市">
          <el-option
              v-for="city in cities"
              :key="city.value"
              :label="city.label"
              :value="city.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 地址 -->
      <el-form-item label="地址">
        <el-input v-model="form.address" placeholder="请输入地址"></el-input>
      </el-form-item>

      <!-- 邮编 -->
      <el-form-item label="邮编" prop="zip">
        <el-input v-model="form.zip" placeholder="请输入邮编"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import provincesCities from '@/assets/provinces-cities.json'; // 导入 JSON 文件
import userlist from '@/api/userlist'; // 引入 userlist.js 文件

export default {
  data() {
    return {
      dialogVisible: false, // 控制弹窗显示
      dialogTitle: '新增联系人', // 弹窗标题
      form: {
        id: '', // ID
        date: '', // 日期
        name: '', // 姓名
        province: '', // 省份
        city: '', // 城市
        address: '', // 地址
        zip: '', // 邮编
      },
      rules: {
        // 表单验证规则
        date: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        zip: [{ required: true, message: '请输入邮编', trigger: 'blur' }],
      },
      provinces: provincesCities.provinces, // 使用导入的省份数据
      cities: [], // 动态加载的城市选项
      isEdit: false,
    };
  },
  methods: {
    // 打开弹窗
    open(title, isEdit, rowData) {
      this.dialogTitle = title;
      this.dialogVisible = true;
      this.isEdit = isEdit;

      if (isEdit && rowData) {
        // 如果是编辑模式，填充已有数据
        //console.log('接收到的数据:', rowData); // 调试日志

        // 将省份名称转换为对应的 value 值
        const provinceValue = this.getProvinceValue(rowData.province);
        const cityValue = this.getCityValue(rowData.city,provinceValue);
        //console.log('省份:', provinceValue);
        //console.log('城市:', cityValue);
        this.form = {
          id: rowData.id || '',
          date: rowData.date || '',
          name: rowData.username || '',
          province: provinceValue || '',
          city: cityValue || '',
          address: rowData.address || '',
          zip: rowData.zip || '',
        };

        // 初始化省份和城市，不清空 city
        this.handleProvinceChange(this.form.province, true);
      } else {
        // 如果是新增模式，清空表单
        this.resetForm();
      }

    },

    // 获取省份对应的 value 值
    getProvinceValue(provinceName) {
      const province = this.provinces.find(p => p.label === provinceName);
      return province ? province.value : '';
    },
    getCityValue(cityName, provinceValue) {
      const city = provincesCities.cities[provinceValue].find(c => c.label === cityName);
      return city ? city.value : '';
    },
    // 获取省份对应的 label 值
    getProvinceLabel(provinceValue) {
      const province = this.provinces.find(p => p.value === provinceValue);
      return province ? province.label : '';
    },

    // 获取城市对应的 label 值
    getCityLabel(cityValue) {
      const city = this.cities.find(c => c.value === cityValue);
      return city ? city.label : '';
    },
    // 关闭弹窗
    handleClose() {
      this.resetForm();
    },

    // 提交表单
    handleSubmit() {
      this.$refs.contactForm.validate((valid) => {
        if (valid) {
          const userInfo = this.convertFormToLabels(this.form);
          console.log('提交的数据:', userInfo);
          if (this.isEdit) {
            // 编辑模式，调用 updateUserList
            userlist.updateUserList(userInfo)
                .then(response => {
                  if(response.data){
                    this.$message.success('用户信息更新成功');
                    this.dialogVisible = false;
                    this.$emit('refreshList'); // 通知父组件刷新列表
                  }
                })
                .catch(error => {
                  this.handleApiError(error);
                });
          } else {
            // 新增模式，调用 addUserList
            userlist.addUserList(userInfo)
                .then(response => {
                  if(response.data){
                    this.$message.success('用户信息新增成功');
                    this.dialogVisible = false;
                    this.$emit('refreshList'); // 通知父组件刷新列表
                  }
                })
                .catch(error => {
                  this.handleApiError(error);
                });
          }
        } else {
          this.$message.error('表单验证失败');
          return false;
        }
      });
    },

    // 处理 API 错误
    handleApiError(error) {
      if (error.response) {
        // 请求已发出，但服务器响应的状态码不在 2xx 范围内
        const errorMessage = error.response.data || '操作失败';
        this.$message.error(errorMessage);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        this.$message.error('请求超时或服务器无响应');
      } else {
        // 在设置请求时发生了一些事情，触发了错误
        this.$message.error('操作失败');
      }
    },
    // 重置表单
    resetForm() {
      this.form = {
        date: '',
        name: '',
        province: '',
        city: '',
        address: '',
        zip: '',
      };
      this.cities = [];
      this.isEdit = false;
    },

    // 处理省份选择变化
    handleProvinceChange(province, isInitialization = false) {
      //console.log('当前省份:', province); // 调试日志
      // 根据省份动态加载城市选项
      this.cities = provincesCities.cities[province] || [];

      // 只有在初始化时不清空 city
      if (!isInitialization) {
        this.form.city = '';
      }
    },

    // 将 form 中的 province 和 city 从 value 转换为 label
    convertFormToLabels(form) {
      const provinceLabel = this.getProvinceLabel(form.province);
      const cityLabel = this.getCityLabel(form.city);

      return {
        id: form.id,
        date: form.date,
        username: form.name,
        province: provinceLabel,
        city: cityLabel,
        address: form.address,
        zip: form.zip,
      };
    },
  },
};
</script>

<style scoped>
/* 自定义样式 */
</style>
